package org.nextive.android.weightapp.utils;

import org.nextive.android.weightapp.R;
import org.nextive.android.weightapp.db.WeightDAO;
import org.nextive.android.weightapp.entities.Weight;

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class WeightCursorAdapter extends CursorAdapter 
{
	
	public WeightCursorAdapter(Context context, Cursor c) 
	{
		super(context, c, true);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) 
	{
		fillData(view, cursor, context);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) 
	{
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflater.inflate(R.layout.history_row, null);
		fillData(view, cursor, context);		
		return view;
	}
	
	private void fillData(View view, Cursor cursor, Context context)
	{
		TextView textViewDate = (TextView) view.findViewById(R.id.textViewWhDate);
		String date = cursor.getString(cursor.getColumnIndex(WeightDAO.WEIGHT_DATE));
		textViewDate.setText(date);
		TextView textViewWeight = (TextView) view.findViewById(R.id.textViewWhWeight);
		double weightValue = cursor.getDouble(cursor.getColumnIndex(WeightDAO.WEIGHT_WEIGHT));
		textViewWeight.setText(Utils.getRoundedWeight(context, weightValue));
	}
	
	@Override
	public Object getItem(int position) 
	{
		Cursor item = (Cursor) super.getItem(position);
		Weight weight = new Weight();
		weight.setId(item.getLong(item.getColumnIndex(WeightDAO.WEIGHT_ID)));
		weight.setDate(item.getString(item.getColumnIndex(WeightDAO.WEIGHT_DATE)));
		weight.setWeight(item.getDouble(item.getColumnIndex(WeightDAO.WEIGHT_WEIGHT)));
		return weight;
	}
}
